<template>
  <view class="home-page">
    <view class="content">
      <view class="tab-option">
        <uni-segmented-control
          :current="tabActive"
          :values="items"
          @clickItem="handleChangeTab"
          styleType="text"
          activeColor="#4CC1EE"
        ></uni-segmented-control>
      </view>
      <view v-show="tabActive === 0">
        <map
          name="map"
          id="MapTest"
          :longitude="longitude"
          :latitude="latitude"
          scale="14"
          show-location
          :markers="markers"
          :style="{ height: mapHeight + 'px' }"
          @markertap="handleClickMarker"
        ></map>
      </view>

      <view v-show="tabActive === 1">
        <scroll-view
          scroll-y
          class="order-list-wrap"
          :style="{ height: mapHeight + 'px' }"
          @scrolltolower="handleLoadMore"
          lower-threshold="70"
        >
          <view v-if="isNullData" class="no-data">
            <van-empty description="暂无数据" />
          </view>

          <view
            v-for="(item, index) in list"
            :key="index"
            @click="handleToOrderDetail(item)"
            class="order-wrap"
          >
            <view class="user-wrap">
              <UserInfoInList
                :type="2"
                :userInfo="{
                  name: item.a1name,
                  address:
                    item.a1areaaddress +
                    item.a1name_address +
                    item.a1doornumber,
                }"
              />

              <view class="status-wrap">
                {{ goodsStatusMapText[item.goods_status] }}
              </view>
            </view>

            <DeliveryManInfo :info="item.express_user" />
          </view>

          <view class="loading" v-if="loading">
            <van-loading color="#0091FF" size="34px" />
          </view>
        </scroll-view>
      </view>

      <view v-show="tabActive === 2">
        <scroll-view
          scroll-y
          class="order-list-wrap"
          :style="{ height: mapHeight + 'px' }"
        >
          <view v-if="isNullData" class="no-data">
            <van-empty description="暂无数据" />
          </view>

          <view
            v-for="(item, index) in list"
            :key="index"
            @click="handleToOrderDetail(item)"
            class="order-wrap"
          >
            <view class="user-wrap">
              <UserInfoInList
                :type="1"
                :userInfo="{
                  name: item.a2name,
                  address:
                    item.a2areaaddress +
                    item.a2name_address +
                    item.a2doornumber,
                }"
              />

              <view class="status-wrap">
                {{ goodsStatusMapText[item.goods_status] }}
              </view>
            </view>

            <DeliveryManInfo :info="item.express_user" />
          </view>

          <view class="loading" v-if="loading">
            <van-loading color="#0091FF" size="34px" />
          </view>
        </scroll-view>
      </view>
    </view>
    <van-toast id="van-toast" />
  </view>
</template>

<script>
const app = getApp();

import Toast from "wxcomponents/vant/toast/toast";
import DeliveryManInfo from "@/components/DeliveryManInfo/index.vue";
import UserInfoInList from "@/components/UserInfoInList/index.vue";

export default {
  components: {
    DeliveryManInfo,
    UserInfoInList,
  },
  data() {
    return {
      markers: [],
      latitude: "",
      longitude: "",
      showModal: false,
      tabActive: 0,
      pageIndex: 1,
      pageSize: 10,
      mapHeight: 500,
      list: [],
      loading: false,
      hasMoreData: false,
      isNullData: false,
      goodsStatusMapText: {
        0: "待接单",
        1: "已接单",
        2: "配送中",
        3: "已完成",
      },
      items: ["我要寄件", "在寄包裹", "待收包裹"],
    };
  },
  onLoad() {
    const windowInfo = uni.getWindowInfo();
    const { windowHeight } = windowInfo;

    this.mapHeight = windowHeight - 36;
    // if (app.globalData.userInfo.express_type !== 1) {
    //   this.handleGetGps();
    // }
    this.handleGetGps();
  },
  onShow() {
    // if (app.globalData.userInfo.express_type !== 1) {
    //   this.handleGetExpressDeliverySetMap();
    // }
    this.handleGetExpressDeliverySetMap();
  },
  mounted() {},
  methods: {
    handleToOrderDetail(item) {
      const { oid } = item;

      uni.navigateTo({
        url: "/pages/myFeature/orderList/orderDetail?oid=" + oid,
      });
    },
    handleGetGps() {
      const that = this; // 获取当前地理位置（前台定位）

      uni.getLocation({
        type: "wgs84", // 使用 GPS 定位
        success(res) {
          console.log(555555);
          const { longitude, latitude } = res;

          that.latitude = latitude;
          that.longitude = longitude;
          app.globalData.latitude = latitude;
          app.globalData.longitude = longitude;
          that.handleGetExpressDeliverySetMap(); // 启动位置变化监听（模拟后台定位效果，需保持页面运行状态）

          uni.onLocationChange((location) => {
            that.latitude = location.longitude;
            that.longitude = location.latitude;
            app.globalData.latitude = location.longitude;
            app.globalData.longitude = location.latitude; // 处理位置变化逻辑...
          });
        },
        fail(err) {
          if (err.errMsg.includes("authorize:fail")) {
            // 用户未授权地理位置信息
            uni.showModal({
              title: "提示",
              content: "为了提供更好的服务，需要您开启位置授权",
              showCancel: false,
              confirmText: "去授权",
              success(res) {
                if (res.confirm) {
                  // 重新尝试获取位置信息以触发授权提示
                  uni.getLocation({
                    type: "wgs84",
                  });
                }
              },
            });
          } else {
            console.error("获取位置失败", err);
            that.handleTipAuthLocation();
          }
        },
      });
    },
    handleClickMarker(data) {
      const { detail } = data;
      const { markerId } = detail;

      wx.navigateTo({
        url: "/pages/send/deliveryDetails?id=" + markerId,
      });
      return;
    },
    handleChangeTab(res) {
      const { currentIndex } = res;

      this.tabActive = currentIndex;
      this.handleInitPageInfo();
      if (currentIndex === 1) {
        this.handleGetOrderList();
      } else if (currentIndex === 2) {
        this.handleGetOrderList();
      }
    },
    handleTipAuthLocation() {
      const that = this;

      wx.getSetting({
        success: function (res) {
          let status = res.authSetting;
          console.log(status);
          if (!status["scope.userLocation"]) {
            wx.showModal({
              title: "是否授权使用定位！",
              content:
                "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
              success: function (tip) {
                console.log(tip);
                if (tip.confirm) {
                  wx.openSetting({
                    success: function (data) {
                      let status = data.authSetting;

                      if (!status["scope.userLocation"]) {
                        that.handleTipAuthLocation();
                      } else {
                        that.handleGetGps();
                      }
                    },
                  });
                } else {
                  //console.log('用户拒绝打开设置界面')
                }
              },
            });
          }
        },
      });
    },

    handleGetExpressDeliverySetMap() {
      const { latitude, longitude } = this;

      console.log('latitude+++++',latitude)
      console.log('longitude+++++',longitude)

      if (latitude) {
        app
          .request(
            {
              lat: latitude, // latitude
              lnt: longitude, // longitude
            },
            "/api/logistics/terminal/search_express"
          )
          .then((res) => {
            console.log(res);
            const { code, data } = res;

            if (code === 1) {
              let arr = data.map((item) => {
                return {
                  ...item,
                  id: item.express_id,
                  title: item.entity_name,
                  latitude: item.last_location.lat,
                  longitude: item.last_location.lng,
                  iconPath: "/static/image/kd-icon.png",
                  width: 30,
                  height: 30,
                };
              });
              this.markers = arr;
            }
          });
      }
    },

    handleInitPageInfo() {
      this.pageIndex = 1;
      this.hasMoreData = false;
      this.isNullData = false;
      this.list = [];
    },

    handleGetOrderList() {
      const { tabActive, pageIndex, pageSize } = this;

      this.loading = true;
      app
        .request(
          {
            goods_status: tabActive,
            page: pageIndex,
            limit: pageSize,
          },
          "/api/logistics/order/user_list"
        )
        .then((res) => {
          const { code, data, msg } = res;

          if (code === 1) {
            let getList = data.data || [];
            let list = this.list;

            const newList = list.concat(getList);
            let hasMoreData = true;
            let isNullData = false;

            if (getList.length < pageSize || !getList.length) {
              hasMoreData = false;
            }

            if (pageIndex === 1 && !getList.length) {
              isNullData = true;
            }

            this.hasMoreData = hasMoreData;
            this.isNullData = isNullData;
            this.list = newList;
          } else {
            Toast(msg);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },

    handleLoadMore() {
      const { loading, pageIndex, hasMoreData } = this;

      if (loading === false && hasMoreData) {
        this.loading = true;
        this.isNullData = false;
        this.pageIndex = pageIndex + 1;
        this.handleGetOrderList();
      }
    },
  },
};
</script>

<style lang="less">
page {
  width: 100%;
  height: 100%;
}

.home-page {
  width: 100%;
  height: 100%;

  .content {
    width: 100%;
    height: 100%;
    .order-list-wrap {
      background-color: #f2f2f2;
      .order-wrap {
        margin-bottom: 12rpx;
        background-color: #fff;
        .user-wrap {
          width: 100%;
          padding-right: 20rpx;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .status-wrap {
            white-space: nowrap;
            font-size: 26rpx;
            color: #ff9600;
          }
        }
      }
    }

    .loading {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100rpx;
    }
  }

  #MapTest {
    width: 100%;
  }
}
</style>
